/**
 * 新建统计项目弹出框
 */
import React from 'react';
import { inject, observer } from 'mobx-react';
import { WeaDialog , WeaFormItem , WeaInput , WeaRightMenu,WeaLocaleProvider} from 'ecCom';
import {WeaSwitch} from 'comsMobx';
import { Button ,Modal ,message} from 'antd';
import * as mobx from 'mobx';
import Formular from './formular';
import trim from 'lodash/trim';
import toString from 'lodash/toString';
const getLabel = WeaLocaleProvider.getLabel;

@inject('wfCusReportAddStore')
@observer
export default class AddCountProDialog extends React.Component{
    constructor(props){
        super(props);
        this.state={

		}
    }
    doInit(){

    }
    render(){
        const { wfCusReportAddStore } =this.props;
        const { proJectAddModalShow , proJectModalParams = {},browserFieldProps,
                formulaName = '',setFormulaName,groupData,groupOptions,formulaInfo,proJectTitle,formulaForm} = wfCusReportAddStore;
        const {formulaDesc = '',formula = '',} = proJectModalParams;
        let detailTable = this.getDetailTable();
        let item = {
            colSpan : 2,
            conditionType:"INPUT",
            domkey:["formulaName"],
            fieldcol:18,
            isQuickSearch:false,
            label:getLabel(386255,'公式名称'),
            labelcol:6,
            rules:"required|string",
            value:formulaName,
            viewAttr:3,
            className:"count_project_name",
            inputType:'multilang'
        };
        return(
            <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@9nturf`}
                visible={proJectAddModalShow}
                icon={'icon-coms-workflow'}
                iconBgcolor='#0079DE'
                title={getLabel(386303,"新建统计项目")}
                buttons={[
                	<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@30b97p@doSaveFormula`} type="primary" onClick={this.doSaveFormula.bind(this)}>{getLabel(86,' 保存 ')}</Button>
                ]}
                closable={true}
                onCancel={this.doCancel}
                style={{width:"962px", height:"541px"}}
                moreBtn={{datas:this.getRightMenu(),collectParams:{favname:getLabel(386306,"编辑统计项目"), favouritetype:2}}}
            >
                <div className="add-count-project-dialog">
                    <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@dg83pm`}
                        collectParams={{favname:getLabel(386306,"编辑统计项目"), favouritetype:2}}
                        datas={this.getRightMenu()}
                    >
                        <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@c7qg65`}
                                // label={`${item.label}`}
                                label={getLabel(386255,'公式名称')}
                                labelCol={{span: `${item.labelcol}`}}
                                wrapperCol={{span: `${item.fieldcol}`}}
                                error={formulaForm.getError(item)}
                                tipPosition={'bottom'}>
                                <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@vur3tz`} fieldConfig={item} form={formulaForm} onChange={(v)=>{

                                    let endObj = this.checkLen(100,v.formulaName.value);
                                    if(endObj.isPassed){
                                        setFormulaName(v.formulaName.value);
                                    }else{
                                        message.destroy();
                                        message.warning(getLabel(386256,' 统计项目名称最多不能超过100个字符！ '));
                                        setTimeout(()=>{
                                            formulaForm.updateFields({formulaName:{value:endObj.endStr}},false)
                                            setFormulaName(endObj.endStr);
                                        },10)
                                    }
                                    }}/>
                            </WeaFormItem>
                        <Formular ecId={`${this && this.props && this.props.ecId || ''}_Formular@9z15go`}
                            formularSelects = {groupOptions}
                            formularLeftDatas={groupData}
                            formularRightDatas={formulaInfo}
                            formulaDesc={formulaDesc}
                            formula = {formula}
                            resetState = {proJectAddModalShow}
                            detailTable = {detailTable}
                            browserFieldProps = {browserFieldProps}
                            ref={'formulaComponent'}
                            />
                    </WeaRightMenu>
                </div>
            </WeaDialog>
        )
    }
    getRightMenu(){
        return [{
            key:'1',
            disabled: false,
            icon:<i className='icon-coms-Preservation'/> ,
            content:getLabel(86,' 保存 '),
            onClick: key => this.doSaveFormula(),
        }]
    }
    //检测字符长度
    checkLen(endLen,str){
        //字节60之内
        let codeLen = 0,endStr=str,isPassed=true;
        for(let i=0,len = str.length;i<len;i++){
            if ((str.charCodeAt(i)<=255)){
                codeLen=codeLen+1;
                if(codeLen>endLen){
                    isPassed=false;
                    endStr = str.substring(0,i);
                    break;
                }
            }else{
                codeLen=codeLen+3;
                if(codeLen>endLen){
                    isPassed=false;
                    endStr = str.substring(0,i);
                    break;
                }
            }
        }
        return {endStr,isPassed}
    }
    //

    doSaveFormula(){
    	const {wfCusReportAddStore} = this.props;
		const formulaComponent = this.refs.formulaComponent;
		const formulaDesc = formulaComponent.getFormulaDesc();
        const formula = formulaComponent.getFormula();

        wfCusReportAddStore.formulaForm.validateForm().then(v=>{
            if(v.isValid){
                if(this.checkFormula(formula)){
                    wfCusReportAddStore.saveFormula(formulaDesc,formula);
                    wfCusReportAddStore.formulaForm.updateFields({formulaName:{value:""}},false);
                    formulaComponent.clearState();
                }else{
                    message.warning(getLabel(386257,' 公式校验失败！ '));
                }
            }else{
                v.showErrors();
                this.setState({log: `${new Date()}`})
            }
        })
    }

    //公式校验
    checkFormula(formula){
    	const regex = /^(COUNT|COUNTA|COUNTBLANK|COUNTIF|SUM|AVG|MAX|MIN|SUMIF|MAXIF|MINIF)\（(.{1,})\）$/;
    	if(regex.test(formula)) {
    		const fun = RegExp.$1;
        	let funContent  = RegExp.$2;
        	if((fun === 'COUNT' || fun === 'COUNTA' || fun === 'COUNTBLANK')) {
        		const regex1 = /^\[-{0,1}\d{1,}\]$/;
        		return regex1.test(funContent);
        	} else {
        		try{
        			//检查是否有[a][b] 格式
                    if(fun === 'SUMIF' || fun === 'MAXIF' || fun === 'MINIF') {
                        const _arr = funContent.split('，');
                        if(_arr.length !== 2) {
                            return false;
                        }
                        funContent =  _arr[0];
                        const thenfield = _arr[1];
                        if(!(/^\[-{0,1}\d{1,}\]$/.test(thenfield))) {
                            return false;
                        }
                    }

        			const regex2  = /\]\[/g;
        			if(regex2.test(funContent)) {
        				return false;
        			}
        			//检查括号数量是否匹配(())
    				const operators = funContent.replace(/\[\-{0,1}\d*?\]/g,'');
    				let leftBrackets =0;
    				let rightBrackets = 0;
    				for(let i = 0 ;i < operators.length;i++) {
    					const operator = operators.charAt(i);
    					if(operator == '（') leftBrackets++;
    					if(operator ==  '）') rightBrackets++;
    				}

    				if(leftBrackets !=  rightBrackets) {
    					return false;
    				}
    				//检查公式是否可以进行运算
    				let _funContent  =  funContent.replace(/\[|\]/g,'');
                    _funContent = _funContent.replace(/\=/g,'==');
    				_funContent = _funContent.replace(/\≥/g,'>=');
    				_funContent = _funContent.replace(/\－/g,'-');
    				_funContent = _funContent.replace(/\×/g,'*');
    				_funContent = _funContent.replace(/\≤/g,'<=');
    				_funContent = _funContent.replace(/\≠/g,'!=');
    				_funContent = _funContent.replace(/\（/g,'(');
    				_funContent = _funContent.replace(/\）/g,')');
    				let result;
    				if(fun === 'COUNTIF' && (_funContent.indexOf('∈') > -1 || _funContent.indexOf('∉') > -1 )) {
    				    result = true;
                    } else {
                        result = eval(_funContent);
                    }
    				if(fun === 'COUNTIF' || fun === 'SUMIF' || fun === 'MAXIF' || fun === 'MINIF') {
    					return typeof result == 'boolean';
    				} else if(typeof result == 'number'){
    					return true;
    				}
        		}catch(e){}
        	}
    	}
    	return false;
    }

    getDetailTable(){
        const _regex = /^(COUNT|COUNTA|COUNTBLANK|COUNTIF|SUM|AVG|MAX|MIN|SUMIF|MAXIF|MINIF)\（(.{1,})\）$/;
    	const {groupSelectedKeys,groupData,proJectDataSource} = this.props.wfCusReportAddStore;
        let _groupSelectedKeys = mobx.toJS(groupSelectedKeys);
    	let detailTable  = '';
        let _projectDS = mobx.toJS(proJectDataSource);
        const regex  = /\[(-{0,1}\d{1,})\]/;
        _projectDS && _projectDS.map(o=>{
        	const formula = o.formula.props.children;
            if(_regex.test(formula)) {
                const funContent = RegExp.$2;
                this.getFormulaFieldIds(regex, funContent, _groupSelectedKeys)
            }
		})
        mobx.toJS(groupData).map(o => {
            const index  = _groupSelectedKeys.indexOf(toString(o.id));
            if(index >= 0) {
                if(o.viewtype == 1) {
                    detailTable = o.tabletype;
                }
            }
        })
		return detailTable;
    }

    getFormulaFieldIds(regex,formula,ids = []){
        if(regex.test(formula)) {
        	let id  = RegExp.$1;
        	ids.indexOf(id) === -1 && ids.push(id);
        	let _formula  = formula.replace(new RegExp("\["+id+"\]","g"),'');
            this.getFormulaFieldIds(regex,_formula,ids);
		}
	}

    doCancel = () => {
    	const {wfCusReportAddStore} = this.props;
    	wfCusReportAddStore.setProJectAddModalShow(false);
    	const formulaComponent = this.refs.formulaComponent;
    	formulaComponent.clearState();
    }
}
